import { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import Page from "@/src/components/page"
import { Image, View, Button, Text } from "@tarojs/components";
import { UserState } from '@/src/dva/models/user'
import './index.scss'
import Api from '@/src/lib/api/api';
import { State } from '@/src/dva/state';
import Taro from '@tarojs/taro'
import PageWarpper, { PageWarpperContext } from '@/src/components/page-warpper';
import GoodsCartModel from '@/src/lib/models/goods_cart_model';
// import model from '@/src/lib/models/model';
import Global from '@/src/lib/global';

interface GroupBookingState {
    orderid: string,
    data: any,
    listImg: any,
    is: any,//是否为团长
    user?: any,
    num: number,
    obj: any,
    len: number,
    iscountDown: boolean
}
interface GroupBookingProps {
    user: UserState
}


class GroupBooking extends Component<GroupBookingProps, GroupBookingState> {
    static contextType = PageWarpperContext
    timer: any
    constructor(props) {
        super(props)
        this.state = {
            orderid: "",//拼团订单id100386
            data: {},//订单数据
            listImg: [],//头像数据
            is: '0',//0显示立即参团,1显示给好友发请求
            num: 0,
            obj: {
                d: 0,
                h: 0,
                m: 0,
                s: 0
            },//倒计时
            len: 2,
            iscountDown: true,//是否拼单成功
        }
    }
    onShareAppMessage() {
        const data = this.state;
        return {
            title: '好友拼团',
            path: `/pages/group-booking/index?orderid=${this.state.orderid}&is=0`,
            data: {
                data
            }
        }
    }
    onLoad(e: any) {
        console.log(e)
        if (e.orderid) {
            this.setState({
                orderid: e.orderid,
                is: e.is
            }, () => {
                this.getdetai()
            })
        }
        // this.getdetai()
    }
    // 获取
    getdetai = () => {
        const orderid = this.state.orderid
        Api.pintuan_detail({ orderid }).then((res: any) => {
            console.log(res)
            if (res.issuccess != 1) return
            const { data } = res;
            let listImg = JSON.parse(JSON.stringify(data.pintuan_userlist));
            const pintuan_neednum = data.pintuan_neednum;
            const num = pintuan_neednum - listImg.length
            if (pintuan_neednum - listImg.length > 0) {

                for (let i = 0; i < num; i++) {
                    listImg.push('/resources/images/noe.png')
                }
                console.log(listImg)
            }
            this.setState({
                data,
                listImg,
                num,
                len: data.pintuan_userlist.length
            }, () => {
                this.countDown(data.pintuan_endtime)
            })
        })
    }
    // 立即参团
    tuxedo = () => {
        const { user } = this.props;
        const data = this.state.data
        if (!user.isLogin) {
            let ctx = this.context
            ctx.loginCompentRef.current.show()
            return
        }
        if (data.pintuan_isend == 1) {
            Taro.showToast({
                title: '该拼团已结束',
                icon: 'none',
                duration: 2000
            })
            return
        }
        let cartModel: GoodsCartModel = {
            goodsid: data.goods_id,
            hanliang: data.goods_hanliang || '无',
            id: "",
            kouwei: data.goods_kouwei,
            num: "1",
            pic: data.goods_pic,
            realprice: data.goods_realprice,
            showprice: data.goods_showprice,
            tip: data.goods_tip,
            title: data.goods_title,
            type: '3',
            loc_isSelling: true,
            orderid: data.orderid.toString(),
            freetitle: undefined
        }
        Global.redirectTo("/pages/order-confirm/index", {
            package: "subpackages",
            params: {
                models: [cartModel]
            }
        })
    }
    // 倒计时
    countDown = (endTime) => {
        const num = this.state.data.pintuan_neednum;
        const len = this.state.len;
        console.log('num', num)
        console.log('len', len)
        if (num == len) {
            clearInterval(this.timer)
            this.setState({
                iscountDown: false
            })
            return
        }

        const end = endTime.replace(/-/g, '/');
        console.log('end', end)
        const endTims = new Date(end).getTime();
        this.timer = setInterval(() => {
            let date = new Date().getTime();
            let residueTime = endTims - date;
            let day = 0, hour = 0, minute = 0, second = 0;
            day = parseInt((residueTime / (24 * 60 * 60 * 1000)).toString());//天
            let shengyu = residueTime % (24 * 60 * 60 * 1000)
            hour = parseInt((shengyu / (60 * 60 * 1000)).toString())//时
            shengyu = shengyu % (60 * 60 * 1000)
            minute = parseInt((shengyu / (60 * 1000)).toString())//分
            shengyu = shengyu % (60 * 1000);
            second = Math.round(shengyu / 1000);
            // console.log('day', day)
            // console.log('hour', hour)
            // console.log('minute', minute)
            // console.log('second', second)
            if (day <= 0) {
                day = 0
            }
            if (hour <= 0) {
                hour = 0
            }
            if (minute <= 0) {
                minute = 0
            }
            if (second < 0) {
                second = 0
                clearInterval(this.timer)
                // return
            }
            const obj = {
                d: day,
                h: hour,
                m: minute,
                s: second
            }
            this.setState({
                obj
            })
        }, 1000)
    }
    // 清除定时器
    creaCountDown = () => {
        clearInterval(this.timer)
    }
    onHide() {
        console.log('离开页面')
        clearInterval(this.timer)

    }
    componentDidHide() {
        console.log('离开页面')
        clearInterval(this.timer)

    }
    // 
    examine = () => {
        const { user } = this.props;
        // const data = this.state.data
        if (!user.isLogin) {
            let ctx = this.context
            ctx.loginCompentRef.current.show()
            return
        }
        const is = this.state.is;
        const iscountDown = this.state.iscountDown
        console.log('sss')
        
        if (is == 0 && iscountDown) return
        const orderid = this.state.orderid
        Global.redirectTo("pages/order-detail/index", {
            package: "subpackages",
            params: {
                orderId: orderid,
                type: '3'
            }
        })
    }
    // 返回首页
    goIndex=()=>{
        Taro.switchTab({
            url: '/pages/home/index'
        })
    }
    // goNavProce
    goNavProce=()=>{
        const data = this.state.data;
        Global.redirectTo("/pages/goodsdetail/index", {
            package: "subpackages",
            params: {
                id: data.goods_id
            }
        })
        console.log('data',data)
    }



    render() {
        const { data, listImg, is, num, obj, len, iscountDown } = this.state;
        // console.log(len)
        return (
            <Fragment>
                <Page navigationBar={{ title: "拼团详情", backgroundColor: "#DC3D37" }} is={true} creaTime={this.creaCountDown} >
                    <View className="tops"></View>

                    <View className="conter">
                        {
                           iscountDown ?null:  <View className="pinSuccer dis">
                                <Image src={Global.loadImage('succes.png')} className="succes"></Image>
                                <Text className="textSucces">拼单成功</Text>
                            </View>
                        }
                        {/* 商品 */}
                        <View className="shopping" onClick={this.goNavProce}>
                            <View className="shpLeft">
                                <Image src={data.goods_pic} className="shpLeft"></Image>
                            </View>
                            <View className="rig">
                                <View className="rigTop">
                                    {data.goods_title}{data.goods_kouwei}{data.goods_hanliang}
                                </View>
                                <View className="rigBotm">
                                    <View className="prics dis">¥{data.goods_realprice}</View>
                                    <View className="prics_1 dis">¥{data.goods_showprice}</View>
                                </View>
                            </View>
                        </View>
                        {/* 倒计时 */}
                        {
                            iscountDown ? (<View className="countDown">
                                <View className="text">即将结束</View>
                                <View className="day dis">{obj.h}</View>
                                <View className="dian">:</View>
                                <View className="day dis">{obj.m}</View>
                                <View className="dian">:</View>
                                <View className="day dis">{obj.s}</View>
                            </View>) : null
                        }
                        {/* <View className="countDown">
                            <View className="text">即将结束</View>
                            <View className="day dis">{obj.h}</View>
                            <View className="dian">:</View>
                            <View className="day dis">{obj.m}</View>
                            <View className="dian">:</View>
                            <View className="day dis">{obj.s}</View>
                        </View> */}

                        {/* bount */}
                        {
                            len == data.pintuan_neednum ? null : is == 1 ? <Button className="chars dis" open-type="share">立刻邀请好友拼团</Button> :
                                <View className="chars dis" open-type="share" onClick={this.tuxedo}>立刻参团</View>
                        }

                        {/* 规则 */}
                        {
                            iscountDown ? <View className="guiz dis">拼团规则：好友参团，人数不足退款</View> : null
                        }
                        <View className="line"></View>

                        <View className="itemImg">
                            {
                                listImg.map((item, index) => {
                                    return <View className="imgItem">
                                        <Image src={item} className="noeImg"></Image>
                                        {
                                            index == 0 ? <View className="tuanz dis">团长</View> : null
                                        }
                                    </View>
                                })
                            }
                        </View>

                        {/*  */}
                        {
                            iscountDown ? <View className="tip dis">还差{num}人，赶快邀请好友来参团吧</View> :is==1?<View className="guiz dis">拼团成功，卖家会在48小时内发货</View>:<View className="guiz dis">该单已拼团成功，可以看看别的团哦~</View>
                        }


                        {/*iscountDown true 拼团没有成功  */}
                        {/* {
                            is==1 && iscountDown?<View className="butons dis" onClick={this.examine}>查看订单详情</View>: !iscountDown?<View className="butons dis" onClick={this.examine}>查看订单详情</View>: <View className="butons butons_1  dis" onClick={this.goIndex}>返回首页</View>
                        } */}
                        <View className="butons butons_1  dis" onClick={this.goIndex}>返回店铺首页</View>
                       


                    </View>
                </Page>

            </Fragment>
        )
    }

}
export default connect((state: State) => ({
    user: state.user
}))(PageWarpper()(GroupBooking))